package com.hmall.item.handler;

import com.hmall.common.dto.User;
import com.hmall.util.UserThreadLocal;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录请求拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 在执行controller方法之前进行执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求中取用户ID
        String userId = request.getHeader("authorization");
        //2.通过网关访问
        if (StringUtils.isNotBlank(userId) && StringUtils.equals("2", userId)) {
            User user = new User();
            user.setId(Long.parseLong(userId));
            UserThreadLocal.put(user);
            return true;
        }
        return false;
    }

    /**
     * 在执行之后
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
